package com.mengjing.adcommon.ad

import android.content.Context
import android.util.Log
import android.view.View
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTNativeExpressAd

class InteractionAd(mContext: Context): BaseAd(mContext) {
    private var mCount: Int = 0
    private var mWidth: Int = 0
    private var mHeight: Int = 0

    /**
     * @param codeId 代码位ID
     * @param count 播放数量 1-3
     * @param width 宽度
     * @param height 高度
     */
    fun showAd(codeId: String, count: Int, width: Int, height: Int) {
        mCodeId = codeId
        mCount = count
        mWidth = width
        mHeight = height
        loadAd()
    }

    private fun loadAd() {
        val adSlot = AdSlot.Builder()
            .setCodeId(mCodeId)
            .setAdCount(mCount)
            .setExpressViewAcceptedSize(mWidth.toFloat(), mHeight.toFloat())
            .build()
        
        mTTAdNative.loadInteractionExpressAd(adSlot, AdListener())
    }
    
    private inner class AdListener: TTAdNative.NativeExpressAdListener {
        override fun onError(p0: Int, p1: String?) {
            Log.d(TAG, "onError: load error: code: $p0, message: $p1")
        }

        override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) {
            if (ads == null || ads.size == 0) return

            ads.forEach{
                it.setExpressInteractionListener(AdInteractionListener())
                renderAd(it)
            }
        }
    }

    private inner class AdInteractionListener: TTNativeExpressAd.AdInteractionListener {
        override fun onAdClicked(p0: View?, p1: Int) {
            Log.d(TAG, "onAdClicked: ")
        }

        override fun onAdShow(p0: View?, p1: Int) {
            Log.d(TAG, "onAdShow: ")
        }

        override fun onRenderFail(p0: View?, p1: String?, p2: Int) {
            Log.d(TAG, "onRenderFail: ")
        }

        override fun onRenderSuccess(p0: View?, p1: Float, p2: Float) {
            Log.d(TAG, "onRenderSuccess: ")
        }

        override fun onAdDismiss() {
            Log.d(TAG, "onAdDismiss: ")
        }

    }

    private fun renderAd(ad: TTNativeExpressAd) {
        ad.render()
    }
}